package spring.cloud.tasks.api.analyzer;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import spring.cloud.tasks.api.database.entity.StatisticsDto;
import spring.cloud.tasks.api.domain.zooKeeperClusterAndNameSpace.ZooKeeperCluster;
import spring.cloud.tasks.api.service.ZooKeeperClusterService;
import spring.cloud.tasks.api.utils.Response;

@RequestMapping("/dashboard")
public class DashboardController {
    @Autowired
    private DashboardService dashboardService;
    @Autowired
    private ZooKeeperClusterService zooKeeperService;


    private ZooKeeperCluster checkAndGetZooKeeperCluster(String zooKeeperClusterKey) throws RuntimeException {
        ZooKeeperCluster zooKeeperCluster = zooKeeperService.getZooKeeperCluster(zooKeeperClusterKey);
        if (zooKeeperCluster == null) {
            throw new RuntimeException("zk clsuter " + zooKeeperClusterKey + "不存在");
        }
        return zooKeeperCluster;
    }


    @RequestMapping(value = "/top10LoadJob")
    public Response top10LoadJob(@RequestParam(required = false) String zooKeeperClusterKey)
            throws RuntimeException {
        if (StringUtils.isNotBlank(zooKeeperClusterKey)) {
            ZooKeeperCluster zooKeeperCluster = checkAndGetZooKeeperCluster(zooKeeperClusterKey);
            StatisticsDto statisticsDto = dashboardService.top10LoadJob(zooKeeperCluster.getZooKeeperAddressList());
            return statisticsDto == null ? new Response() : Response.success(statisticsDto.getStatistics());
        }
        return Response.success(dashboardService.top10LoadJobByAllZkCluster());
    }


    @RequestMapping(value = "/top10LoadExecutor")
    public Response top10LoadExecutor(@RequestParam(required = false) String zkClusterKey)
            throws RuntimeException {
        if (StringUtils.isNotBlank(zkClusterKey)) {
            ZooKeeperCluster zkCluster = checkAndGetZooKeeperCluster(zkClusterKey);
            StatisticsDto statisticsDto = dashboardService.top10LoadExecutor(zkCluster.getZooKeeperAddressList());
            return statisticsDto == null ? new Response() : Response.success(statisticsDto.getStatistics());
        }
        return Response.success(dashboardService.top10LoadExecutorByAllZkCluster());
    }


}
